//
//  KK_TabBarView.m
//  iwtsa
//
//  Created by Kratos on 13-12-26.
//  Copyright (c) 2013年 ipointek. All rights reserved.
//

#import "KK_TabBarView.h"
#import "NSString+Size.h"

#define ButtonFontName @"STHeitiSC-Medium"
#define ButtonFontSize 16
#define ButtonFrameGAP 0.0f
#define LEDViewDefineHeight 2.0f

@interface KK_TabBarView()
//选中按钮时的指示标签
@property (nonatomic , strong) UIView *LEDView;

@property (nonatomic , assign) CGRect oldButtonRect;
/**
 * 将滑动内容界面滚动到能见界面的中间
 * @param contentRect 所选目标的位置大小
 * @return
 * @author Kratos
 */
- (void)scrollToContentCenter:(CGRect)contentRect;


/**
 * 按钮事件
 * @param sender UIButton
 * @return
 * @author Kratos
 */
- (void)selectButton:(id)sender;


@end

@implementation KK_TabBarView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/**
 * 初始化对象
 * @param data 显示对象
 * @param frame 滑动位置大小
 * @param colorRGB 选择时横条颜色及字体颜色
 * @return KK_TabBarView
 * @author Kratos
 */
- (id)initWithDataSource:(NSArray *)data frame:(CGRect)frame selectedColor:(UIColor *)color
{
    self = [super initWithFrame:frame];
    if (self) {
        _dataSourceArray = [NSMutableArray arrayWithArray:data];
//        _contentButtonsArray = [NSMutableArray new];
        _buttonsWidthArray = [NSMutableArray new];
        
        _selectedIndex = 0;
        _selectedColor = color;
    }
    return self;
}

- (void)initializeContentsViews
{
    //设置背景颜色或图片
//    UIImageView *backgroundImage = [[UIImageView alloc] initWithFrame:self.bounds];
//    [backgroundImage setImage:[UIImage imageNamed:@""]];
    [self setBackgroundColor:[UIColor clearColor]];
    //初始化指示标签
    _LEDView = [[UIView alloc]initWithFrame:CGRectZero];
    [_LEDView setBackgroundColor:_selectedColor];
    
    //数据数量
    NSInteger dataCount = [_dataSourceArray count];
    //按钮使用的字体
    UIFont *buttonFont = [UIFont fontWithName:ButtonFontName size:ButtonFontSize];
    
    float scrollViewContentWidth = ButtonFrameGAP * (dataCount + 1);
    for (int i = 0; i < dataCount; i++) {
        NSString *title = [_dataSourceArray objectAtIndex:i];
        CGFloat buttonWidth = [title calculateSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 40.f) font:buttonFont].width + 10.f;
        
        [_buttonsWidthArray addObject:[NSNumber numberWithFloat:buttonWidth]];
        scrollViewContentWidth += buttonWidth;
    }
    
    //判断现在的活动内容界面的宽度是否比界面短，若短的话将获取的差距平分给每个按钮
    CGFloat widthGap = scrollViewContentWidth - CGRectGetWidth(self.bounds);
    if (widthGap < 0) {
        CGFloat avg = -widthGap / dataCount;
        for (int i = 0; i < dataCount; i++) {
            CGFloat newWidth = [[_buttonsWidthArray objectAtIndex:i]floatValue]+avg;
            [_buttonsWidthArray replaceObjectAtIndex:i withObject:[NSNumber numberWithFloat:newWidth]];
        }
    }
    
    //初始化滑动页面
    _contentsScrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
//    [_contentsScrollView setBackgroundColor:[UIColor clearColor]];
    [_contentsScrollView setContentSize:CGSizeMake(scrollViewContentWidth, CGRectGetHeight(self.bounds))];
    _contentsScrollView.pagingEnabled = NO;
    _contentsScrollView.scrollEnabled = YES;
    _contentsScrollView.showsHorizontalScrollIndicator = NO;
    _contentsScrollView.showsVerticalScrollIndicator = NO;
    
    [self addSubview:_contentsScrollView];
    
    //添加按钮
    int xPos = ButtonFrameGAP;
    for (int i = 0; i < dataCount; i++) {
        NSString *title = [_dataSourceArray objectAtIndex:i];
        //创建按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat buttonWidth = [[_buttonsWidthArray objectAtIndex:i] floatValue];
        [button setFrame:CGRectMake(xPos, 0.0f,buttonWidth ,CGRectGetHeight(self.bounds) - LEDViewDefineHeight)];
        [button.titleLabel setFont:buttonFont];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitle:title forState:UIControlStateSelected];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button setTitleColor:_selectedColor forState:UIControlStateSelected];
        [button addTarget:self action:@selector(selectButton:) forControlEvents:UIControlEventTouchUpInside];
        [button setTag:(100+i)];
        
        //保存按钮到数组
//        [_contentButtonsArray addObject:button];
        //添加按钮到滑动界面
        [_contentsScrollView addSubview:button];
        xPos += (buttonWidth + ButtonFrameGAP);
    }
    
    //设置初始化时选中的按钮并在按钮下添加选中标记
    UIButton *selectedButton = (UIButton*)[self viewWithTag:(_selectedIndex + 100)];;
    [selectedButton setSelected:YES];
    _oldButtonRect = selectedButton.frame;
    [_LEDView setFrame:CGRectMake(selectedButton.frame.origin.x, CGRectGetHeight(selectedButton.frame), CGRectGetWidth(selectedButton.frame), LEDViewDefineHeight)];
    //指示条下一层的灰色条
    UIView *backLineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(selectedButton.frame), CGRectGetWidth(self.bounds), LEDViewDefineHeight)];
    [backLineView setBackgroundColor:[UIColor lightGrayColor]];
    
    [self insertSubview:backLineView belowSubview:_contentsScrollView];
    [_contentsScrollView addSubview:_LEDView];
}

/**
 * 更新数据
 * @return 空
 * @author Kratos
 */
- (void)relodData:(NSArray *)dataSource
{
    //数据数量
    NSArray *allContents = [self subviews];
    for (UIView *contentView in allContents) {
        [contentView removeFromSuperview];
    }
    //    [_contentButtonsArray removeAllObjects];
    [_buttonsWidthArray removeAllObjects];
    [_dataSourceArray removeAllObjects];
    
    [_dataSourceArray addObjectsFromArray:dataSource];
    _selectedIndex = 0;
    [self initializeContentsViews];
}


/**
 * 按钮事件
 * @param sender UIButton
 * @return
 * @author Kratos
 */
- (void)selectButton:(id)sender
{
    __block UIButton *selectedNewButton = (UIButton *)sender;
    //取消当前选择
    if (selectedNewButton.tag != (_selectedIndex + 100))
    {
        UIButton * selectedOldButton = (UIButton*)[self viewWithTag:(_selectedIndex + 100)];
        [selectedOldButton setSelected:NO];
        _selectedIndex = selectedNewButton.tag - 100;
    }
    [selectedNewButton setSelected:YES];
    
    __block typeof(self) self_ = self;
    [UIView animateWithDuration:0.25f animations:^{
        [self_.LEDView setFrame:CGRectMake(selectedNewButton.frame.origin.x, CGRectGetHeight(selectedNewButton.frame), CGRectGetWidth(selectedNewButton.frame), LEDViewDefineHeight)];
        [self_ scrollToContentCenter:selectedNewButton.frame];
        self_.oldButtonRect = selectedNewButton.frame;
    } completion:^(BOOL finished) {
        if ([self_.delegate respondsToSelector:@selector(tabBarView:didSelectIndex:)])
            [self_.delegate tabBarView:self_ didSelectIndex:self_.selectedIndex];
    }];
    
}

/**
 * 将滑动内容界面滚动到能见界面的中间
 * @param contentRect 所选目标的位置大小
 * @return
 * @author Kratos
 */
- (void)scrollToContentCenter:(CGRect)contentRect
{
    CGRect frame = contentRect;
    BOOL flag = _oldButtonRect.origin.x - frame.origin.x > 0 ? YES : NO;
    
    if (flag) {
        CGFloat movedRatio = (_contentsScrollView.contentOffset.x / CGRectGetWidth(_contentsScrollView.frame)) - 1;
        frame.origin.x += movedRatio * CGRectGetWidth(frame);
        
        frame.origin.x += (frame.size.width / 2);
        frame.origin.x -= CGRectGetWidth(_contentsScrollView.frame) / 2;
        frame.size.width = CGRectGetWidth(_contentsScrollView.frame);
        
        if (frame.origin.x < 0) {
            frame.origin.x = 0;
        }
        
        if ((frame.origin.x + frame.size.width) > _contentsScrollView.contentSize.width) {
            frame.origin.x = (_contentsScrollView.contentSize.width - CGRectGetWidth(_contentsScrollView.frame));
        }
    }
    else {
        float offset = CGRectGetWidth(_contentsScrollView.bounds) - CGRectGetWidth(contentRect);
        if (offset > 0) {
            frame.origin.x -= offset/2;
        }
        frame.size.width = CGRectGetWidth(_contentsScrollView.bounds);
    }
    [_contentsScrollView scrollRectToVisible:frame animated:YES];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
